﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 2000;
            string host = "127.0.0.1";

            //创建终结点
            IPAddress ip=IPAddress.Parse(host);
            IPEndPoint ipe=new IPEndPoint(ip,port);

            //创建socket开始监听
            Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            socket.Bind(ipe);
            socket.Listen(0);
            
            Console.WriteLine("等待客户端连接...");

            //接收到 client 连接，为此连接建立新的 socket，并接受消息
            Socket serv = socket.Accept();
            Console.WriteLine("建立连接");
            string recvStr = "";
            byte[] recvBytes=new byte[1024];
            int bytes;
            bytes = serv.Receive(recvBytes, recvBytes.Length, 0);
            recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);

            //给 client 返回消息
            Console.WriteLine($"server get message:{recvStr}");
            string send = "ok! client send message successful";
            byte[] bs = Encoding.ASCII.GetBytes(send);
            serv.Send(bs, bs.Length, 0);
            serv.Close();
            socket.Close();
            Console.ReadKey();
        }
    }
}
